package com.tpp.threat_perception_platform.aop;

import com.tpp.threat_perception_platform.annotation.RequiresPermission;
import com.tpp.threat_perception_platform.permission.PermissionEnum;
import com.tpp.threat_perception_platform.permission.PermissionService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Set;

@Aspect
@Component
public class PermissionAspect {

    @Autowired
    private PermissionService permissionService;

    @Around("@annotation(requiresPermission)")
    public Object checkPermission(ProceedingJoinPoint joinPoint,
                                  RequiresPermission requiresPermission) throws Throwable {

        PermissionEnum[] requiredPermissions = requiresPermission.value();
        String userName = getCurrentUsername();

        if (!StringUtils.hasText(userName)) {
            throw new SecurityException("用户未登录");
        }

        Set<String> userPermissions = permissionService.getCurrentUserPermissions(userName);

        for (PermissionEnum perm : requiredPermissions) {
            if (!userPermissions.contains(perm.getPermission())) {
                throw new SecurityException("没有访问权限：" + perm.getPermission());
            }
        }

        return joinPoint.proceed();
    }


    private String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            return authentication.getName();
        }
        return null;
    }
}